const HOST = require('../../config.js').host

var app = getApp()


Page({
    data: {
        total: 0,
        selectAllBtn: 'circle',
        isSelectAll: false,
        ceil: 99,

        selectedGoods: [

        ],

        selectedGoodIdx: [

        ],

        goods: [
            // {
            //     selected: false, // 选中状态
            //     amount: 1, // 数量

            //     productName: '花生酥',
            //     category: '原味',
            //     productImg: [
            //         {
            //             attach: {
            //                 url: '../../assets/images/3.png'
            //             }
            //         }
            //     ],
            //     url: '../../assets/images/1.png',
            //     productPrice: 35
            // }
        ]
    },

    /**
     * 删除
     */
    deleteFromCart (e) {
        let goods = this.data.goods
        goods.splice(e.currentTarget.dataset.idx, 1)

        this.slideRight()

        wx.setStorage({
          key: 'cart',
          data: goods
        })

        this.setData({
            goods,
            total: this.caculateTotal()
        })
    },

    /**
     * 点击收藏触发事件
     */
    like (e) {
        let idx = e.currentTarget.dataset.idx
        let goods = this.data.goods
        let isLike = goods[idx].isLike
        let id = goods[idx].productId

        if (isLike) {
            this.cancelLike(id)
        } else {
            this.uploadLike(id)
        }

        goods[idx].isLike = isLike ? 0 : 1

        this.setData({
            goods
        })
    },

    uploadLike (id) {
        wx.request({
            url: HOST + 'v1/userFavorite',
            data: {
                userId: app.userId,
                productId: id
            },
            method: 'POST',
            success: function(res){
                if (res.data.sysCode === 1) {
                    console.log('喜欢商品成功！')
                }
            }.bind(this)
        })
    },

    cancelLike (id) {
        wx.request({
            url: HOST + 'v1/userFavorite',
            data: {
                userId: this.data.userId,
                productId: id
            },
            method: 'DELETE',
            success: function(res){
                if (res.data.sysCode === 1) {
                    console.log('喜欢商品成功！')
                }
            }.bind(this)
        })
    },

    caculateTotal () {
        const goods = this.data.goods
        let total = 0
        goods.forEach(good => {
            if (good.selected) {
                total += good.total * good.amount
                total = parseFloat(total.toFixed(2))
            }
        })

        return total
    },

    /**
     * 选择商品
     */
    select (e) {
        const idx = e.currentTarget.dataset.idx
        const goods = this.data.goods
        const curPrice = goods[idx].total
        const amount = goods[idx].amount
        let total = this.data.total
        let isSelectAll

        if (goods[idx].selected) {
            goods[idx].selected = false
            total -= curPrice * amount
            isSelectAll = false
        } else {
            goods[idx].selected = true
            total += curPrice * amount
            total = parseFloat(total.toFixed(2))

            isSelectAll = goods.every(v => {
                return v.selected
            })
        }
        this.setData({
            goods,
            total,
            isSelectAll
        })
    },

    /**
     * 全选
     */
    selectAll () {
        let isSelectAll = this.data.isSelectAll
        let goods = this.data.goods
        let total = 0

        isSelectAll = isSelectAll ? false : true

        goods.forEach(v => {
            v.selected = isSelectAll
            total += v.total * v.amount
            total = parseFloat(total.toFixed(2))
        })

        total = isSelectAll ? total : 0

        this.setData({
            goods,
            total,
            isSelectAll
        })
    },

    clickMore () {
        wx.switchTab({
            url: '../home/home'
        })
    },

    /** 加减商品数量 */
    addAmount (e) {
        const idx = e.currentTarget.dataset.idx
        const goods = this.data.goods
        let total = this.data.total

        goods[idx].amount += 1

        if (goods[idx].selected) {
            total += goods[idx].total
            total = parseFloat(total.toFixed(2))
            console.log(total)
        }

        this.modifyCart(goods)

        this.setData({
            goods,
            total
        })
    },

    subAmount (e) {
        const idx = e.currentTarget.dataset.idx
        const goods = this.data.goods
        let total = this.data.total
        //团购票数组（是否存在团购票）
        // let groupTicket = [];
        // let categItem = this.data.goods;
        // for (let i in categItem) {
        //   // let item = i.category;
        //   let item = categItem[i].category.match(/：(\S*)；/)[1] || "";

        //   if (item == "团购票" || item == "团购票VIP") {
        //     groupTicket.push(Number(i));
        //   }
        // }
        
        // let isGroupSub = (groupTicket.length != 0) && (groupTicket.indexOf(idx) != -1) && (goods[idx].amount <= 7)



        if (goods[idx].amount === 1) {
            return
        }
//团购票
        // if (isGroupSub) {
        //   goods[idx].amount = 7;
        // } else {
          goods[idx].amount -= 1
        // }

        if (goods[idx].selected) {
            total -= goods[idx].total
            total = parseFloat(total.toFixed(2))
        }

        this.modifyCart(goods)

        this.setData({
            goods,
            total
        })
    },

    modifyCart (goods) {
        wx.setStorageSync('cart', goods)
    },

    /**
     * 结算
     */
    settle () {
        let cartIdx = ''
        let buy = this.data.goods.filter((v, idx) => {
            if (v.selected) {
                cartIdx += idx + ','
            }

            return v.selected
        })

        if (buy.length) {
            app.globalData.order.goods = buy

            wx.navigateTo({
                url: '../settlement/list/list?total=' + this.data.total + '&cartIdx=' + cartIdx + '&useTicket=' + 0
            })
        } else {
            wx.showModal({
                title: '购物车',
                content: '请选择至少一件商品',
                showCancel: false
            })
        }

    },

    /** 左滑 **/
    touchstart (e) {
       this.setData({
           x: e.changedTouches[0].pageX,
           touchIdx: e.currentTarget.dataset.idx
       })
    },

    touchend (e) {
        let idx = parseInt(e.currentTarget.dataset.idx);
        let curX = e.changedTouches[0].pageX
        if (this.data.x - curX > 50) {
            this.slideLeft()
        } else if (curX - this.data.x > 50) {
            this.slideRight()
        }
    },

    slideLeft () {
        let animation = wx.createAnimation({
                duration: 200,
                timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
                delay: 0,
                transformOrigin: '50% 50% 0',
            })
            animation.left(-60).step()
            this.setData({
                animation: animation.export()
            })
    },

    slideRight () {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
            delay: 0,
            transformOrigin: '50% 50% 0',
        })
        animation.left(0).step()
        this.setData({
            animation: animation.export()
        })
    },

    /** 生命周期 **/
    onShow () {
      //扩展数组
      Array.prototype.del = function (dx) {
        if (isNaN(dx) || dx > this.length) { return false; }
        this.splice(dx, 1);
      } 

        const goodsInCart = wx.getStorageSync('cart');
        if (wx.getStorageSync('cart')){
          goodsInCart.forEach((thing,index) => {
            thing.category = ''
            thing.productSpec.forEach((spec, idx) => {
                thing.category += spec.specName + '：' + spec.productSpecItem[thing.selectedCategory[idx]].itemName + '；'
                console.log(thing.category);
            });
        })
          //清除购物车门票
          for (let i = goodsInCart.length - 1;i>=0;i--) {
            if (goodsInCart[i].useTicket == 1) {
              goodsInCart.del(i);
            }
          }
          wx.setStorage({
            key: 'cart',
            data: goodsInCart
          })


        this.setData({
            goods: goodsInCart.map(v => {
                v.selected = false
                return v
            }),
            ceil: app.globalData.ceil,
            isSelectAll: false,
            total:0
        });
    }
    }

})
